package com.lalameow.serverlogingate.utiles;

import com.lalameow.packet.pojo.MdsInfo;
import com.lalameow.serverlogingate.config.NetGateServerConfig;
import lombok.Getter;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/11
 * 时间: 8:05
 * 功能：请进行修改
 */
@Component
public class ModUtils {
    @Autowired
    private NetGateServerConfig netGateServerConfig;
    @Getter
    private List<MdsInfo> vaildModList=new ArrayList<>();
    public void scanMods() throws IOException {
        vaildModList.clear();
        File versionFile=new File(netGateServerConfig.getModspath());
        if(!versionFile.exists()){
            versionFile.mkdirs();
        }
        Collection<File> fileCollection= FileUtils.listFiles(versionFile,new String[]{"jar","litemod"},true);
        for (File file : fileCollection) {
            vaildModList.add(getFileMd5(file));
        }
    }

    /**
     * 校验mod
     * @param mdsInfo
     * @return true为校验通过，false 为校验失败
     */
    public boolean vaildMod(MdsInfo mdsInfo){
        for (MdsInfo info : vaildModList) {
            if(info.equals(mdsInfo)){
                return true;
            }
        }
        return false;
    }
    private  MdsInfo getFileMd5(File file) throws IOException {
        MdsInfo mdsInfo=new MdsInfo();
        FileInputStream fileInputStream=new FileInputStream(file);
        mdsInfo.setMdsMd5( DigestUtils.md5Hex(fileInputStream));
        mdsInfo.setMdsHash(DigestUtils.sha1Hex(fileInputStream));
        mdsInfo.setMdsName(file.getName());
        IOUtils.closeQuietly(fileInputStream);
        return mdsInfo;
    }

    public static String getRandomKey(){
        String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        return afterShuffle.substring(2, 8);
    }
}
